<template>
  <el-select v-if="hasGroup" style="display:absolute;" clearable @change="onChange" v-model="key" placeholder="请选择">
    <el-option-group
      v-for="group in options"
      :key="group.label"
      :label="group.label">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-option-group>
  </el-select>
  <el-select v-else style="display:absolute;" clearable @change="onChange" v-model="key" placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</template>

<script>


  const toOption = data =>{
    const opt = [];
    let hasGroup = false;
    for (const {group} of data) {
      if(group){
        hasGroup = true;
        break;
      }
    }
    if(hasGroup){

    }else{
      for (const {key,value} of data) {
        opt.push({
          label:value,
          value:key
        });
      }
    }
    return {group:hasGroup,options:opt};
  }

  export default {

    async mounted(){
      if(this.value)
        this.key = this.value;
      const data = await this.$code.load(this.type,this.code);
      const {group,options} = toOption(data);
      this.hasGroup = group;
      this.options = options;
    },

    props: {

      code: {
        type: String
      },

      type: {
        type: String,
        default: 'enum'
      },

      value:{
        type:String,
        default:''
      }

    },

    data() {
      return {
        options:[],
        hasGroup:false,
        key:''
      }
    },

    watch:{
      value(newVal){
        this.key = newVal;
      }
    },

    methods:{

      onChange(){
        this.$emit('input',this.key);
      }

    }

  }

</script>
